"use client";

import { Loader2, TriangleAlert } from "lucide-react";
import { useMemo, useState } from "react";

import { useDailyOutputsQuery } from "@/hooks/use-daily-outputs-query";
import { useProjectsQuery } from "@/hooks/use-projects-query";
import { downloadCSV } from "@/lib/csv";
import type { OutputsPaginated, ProjectSummary } from "@/lib/types";

interface DailyReportsViewProps {
  initialOutputs: OutputsPaginated;
  initialDate: string;
  initialProjects: ProjectSummary[];
}

export function DailyReportsView({
  initialOutputs,
  initialDate,
  initialProjects,
}: DailyReportsViewProps) {
  const [selectedDate, setSelectedDate] = useState(initialDate);
  const [selectedProject, setSelectedProject] = useState<string>("");

  const { data: projects } = useProjectsQuery(initialProjects);

  const {
    data: outputs,
    isLoading,
    error,
  } = useDailyOutputsQuery({
    initialData: initialOutputs,
    from: selectedDate,
    to: selectedDate,
    projectId: selectedProject || undefined,
    pageSize: 100,
  });

  const records = useMemo(() => outputs?.items ?? [], [outputs]);
  const total = outputs?.meta.total ?? 0;
  const hasRecords = records.length > 0;

  const exportRows = useMemo(
    () =>
      records.map((item) => ({
        projectName: item.projectName,
        reporterName: item.reporterName,
        date: item.date,
        value: item.value,
        note: item.note ?? "",
      })),
    [records],
  );

  const handleExport = () => {
    if (!hasRecords) {
      return;
    }

    downloadCSV(
      `daily-outputs-${selectedDate}${selectedProject ? `-${selectedProject}` : ""}.csv`,
      [
        { key: "projectName", header: "项目" },
        { key: "reporterName", header: "上报人" },
        { key: "date", header: "日期" },
        { key: "value", header: "产值" },
        { key: "note", header: "备注" },
      ],
      exportRows,
    );
  };

  const renderTable = () => (
    <div className="overflow-hidden rounded-lg border border-border">
      <table className="min-w-full divide-y divide-border text-sm">
        <thead className="bg-muted/40 text-muted-foreground">
          <tr>
            <th className="px-4 py-3 text-left font-medium">项目</th>
            <th className="px-4 py-3 text-left font-medium">上报人</th>
            <th className="px-4 py-3 text-left font-medium">日期</th>
            <th className="px-4 py-3 text-left font-medium">产值</th>
            <th className="px-4 py-3 text-left font-medium">备注</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-border bg-card">
          {records.map((item) => (
            <tr key={item.id}>
              <td className="px-4 py-3">
                <div className="flex flex-col">
                  <span className="font-medium text-foreground">{item.projectName}</span>
                  <span className="text-xs text-muted-foreground">编号：{item.projectId}</span>
                </div>
              </td>
              <td className="px-4 py-3 text-muted-foreground">{item.reporterName}</td>
              <td className="px-4 py-3 text-muted-foreground">
                {new Date(item.date).toLocaleDateString()}
              </td>
              <td className="px-4 py-3 text-muted-foreground">{item.value.toLocaleString()}</td>
              <td className="px-4 py-3 text-xs text-muted-foreground">{item.note ?? "--"}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );

  if (isLoading && !hasRecords) {
    return (
      <div className="space-y-4">
        <div className="rounded-lg border border-border bg-card/60 p-6">
          <div className="flex min-h-[120px] items-center justify-center">
            <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div className="flex flex-col gap-4 rounded-lg border border-border bg-card p-4 shadow-sm md:flex-row md:items-center md:justify-between">
        <div className="space-y-1">
          <p className="text-sm font-medium text-foreground">选择条件</p>
          <p className="text-xs text-muted-foreground">日期或项目变更后会自动刷新日报列表。</p>
        </div>
        <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
          <input
            type="date"
            value={selectedDate}
            onChange={(event) => setSelectedDate(event.target.value || initialDate)}
            className="rounded-md border border-input bg-background px-3 py-2 text-sm shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary"
          />
          <select
            value={selectedProject}
            onChange={(event) => setSelectedProject(event.target.value)}
            className="rounded-md border border-input bg-background px-3 py-2 text-sm shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary"
          >
            <option value="">全部项目</option>
            {projects?.map((project) => (
              <option key={project.id} value={project.id}>
                {project.name}
              </option>
            ))}
          </select>
          <span className="text-xs text-muted-foreground">共 {total} 条</span>
          <button
            type="button"
            onClick={handleExport}
            className="inline-flex items-center rounded-md bg-primary px-3 py-2 text-xs font-medium text-primary-foreground transition hover:bg-primary/90"
            disabled={!hasRecords}
          >
            导出 CSV
          </button>
        </div>
      </div>

      {error ? (
        <div className="flex items-center gap-2 rounded-lg border border-destructive/40 bg-destructive/5 px-4 py-3 text-xs text-destructive">
          <TriangleAlert className="h-4 w-4" />
          日报数据拉取失败，请稍后重试。
        </div>
      ) : null}

      {hasRecords ? (
        renderTable()
      ) : (
        <div className="rounded-lg border border-dashed border-border bg-card/50 p-6 text-sm text-muted-foreground">
          选定条件暂无上报记录。
        </div>
      )}
    </div>
  );
}
